<?php

namespace Biz\service;

use Biz\cache\SToken;
use Biz\model\ShopAuth as ShopAuthModel;
use Biz\model\ShopBasicInfo;
use Doraemon\cache\RedisCache;
use Biz\pockets\serviceTrait\_Async;
use Biz\cache\SVToken as cSVToken;
/**
 * @deprecated
 */
class ShopAuth
{
    use _Async;

    const FORGOT_PASSWD_REDIS = 'forgot_pwd_';

    /**
     * 登陆
     * @param $email
     * @param $password
     * @return bool
     */
    public static function login($email, $password)
    {
        if ($email && $password) {
            $password = self::password($password);
            $uid = ShopAuthModel::getUid($email, $password);
            if ($uid) {
                $token = self::getSapiToken($uid);
                return ['token' => $token, 'uid' => $uid];
            }
        }
        return false;
    }

    /**
     * 用户auth信息添加
     * @param $uid
     * @param $email
     * @param string $password
     * @return mixed
     */
    public static function setAuth($uid, $email, $password)
    {
        if ($uid) {
            $data['status'] = ShopAuthModel::STATUS_NORMAL;
            $data['email'] = $email;
            $data['password'] = $password;
            $info = ShopAuthModel::getByUid($uid);
            if ($info) {
                $result = ShopAuthModel::updateInfo($data, ['uid' => $uid]);
            } else {
                $data['uid'] = $uid;
                $result = ShopAuthModel::addInfo($data);
            }
            return $result;
        }
        return false;
    }


    public static function password($password)
    {
        return md5($password);
    }

    public static function resetPwd($email, $password, $token, $time)
    {
        $md5token = self::createForgetPwdToken($email, $time);
        if ($md5token == $token) {
            RedisCache::del(self::FORGOT_PASSWD_REDIS . $email);
            $password = self::password($password);
            $result = ShopAuthModel::updateInfo(['password' => $password], ['email' => $email]);
            return $result;
        } else {
            throw new \Exception('验证token失效');
        }
    }

    /**
     * 修改密码
     * @param int $uid 用户id
     * @param string $password 修改后的密码
     * @param string $old 原密码
     * @return mixed
     * @throws \Exception
     */
    public static function changePwd($uid, $password, $old)
    {
        $old = self::password($old);
        $password = self::password($password);
        //校验原密码
        if (!ShopAuthModel::hasInfo(['password' => $old, 'uid' => $uid])) {
            throw new \Exception('原密码不正确');
        }
        if ($old == $password) {
            return true;
        }
        $result = ShopAuthModel::updateInfo(['password' => $password], ['uid' => $uid]);
        return $result;
    }

    public static function forgotPwd($email, $origin)
    {
        $time = time();
        $token = self::createForgetPwdToken($email, $time);
        if ($token) {
            RedisCache::setex(self::FORGOT_PASSWD_REDIS . $email, 3 * 60 * 60, $token);
            $url = $origin . '/business_management/forget_password?email=' . $email . '&token=' . $token . '&time=' . $time;
            self::sendFindPasswordUrl($email, $url);
            return true;
        } else {
            throw new \Exception('该用户不存在，请重新输入');
        }
    }

    public static function sendFindPasswordUrl($email, $url)
    {
        self::_async($email, $url);
    }

    public static function _async_sendFindPasswordUrl($email, $url)
    {
        MessageSend::sendEmail($email, 'find_password', ['url' => $url]);
    }

    public static function checkRestPwd($email, $time, $token)
    {
        $md5token = self::createForgetPwdToken($email, $time);
        $rdstoken = RedisCache::get(self::FORGOT_PASSWD_REDIS . $email);
        if ($md5token == $token && $md5token == $rdstoken) {
            return true;
        } else {
            throw new \Exception('不是有效的链接地址');
        }
    }

    private static function createForgetPwdToken($email, $time)
    {
        $info = ShopAuthModel::getByEmail($email);
        if ($info) {
            return md5($info['uid'] . $info['password'] . $time);
        } else {
            throw new \Exception('该用户不存在，请重新输入');
        }
        return false;
    }

    public static function getSapiToken($uid)
    {
        $sapiToken = SToken::getUid2Token($uid);
        if ($sapiToken) {
            $token = $sapiToken;
        } else {
            $token = self::createToken();
        }
        SToken::setUid2Token($uid, $token);
        SToken::setToken($token, SToken::TOKEN_UID, $uid);
        $shopId = SToken::getTokenValue($token, SToken::TOKEN_SHOPID);
        if (!$shopId) {
            $shopId = ShopBasicInfo::getShopId($uid);
        }
        SToken::setToken($token, SToken::TOKEN_SHOPID, $shopId);
        return $token;
    }

    public static function createToken()
    {
        $token = md5(str_shuffle(microtime()));
        return $token;
    }

    public static function admCreateShopVistorSeller($adminUid, $shopId)
    {
        $sapiVToken = cSVToken::getUid2Token($shopId);

        if(empty($sapiVToken)){

            $expire = 3600;//一小时的时间
            
            $sapiVToken = 'v_'.md5(self::createToken() . '-' . $adminUid . '-' . $shopId);

            cSVToken::setUid2Token($shopId, $sapiVToken,$expire);

            cSVToken::setToken($sapiVToken, cSVToken::TOKEN_UID, $shopId,$expire);
            cSVToken::setToken($sapiVToken, cSVToken::TOKEN_APPUID, $shopId,$expire);
            cSVToken::setToken($sapiVToken, cSVToken::TOKEN_SHOPID, $shopId,$expire);

        }


        return [
            'sapi_vtoken' => $sapiVToken,
        ];
    }

    public static function mgtGetAdmShopVistor($sapiVToken = ''){
        return cSVToken::getTokenValue($sapiVToken,cSVToken::TOKEN_UID);
    }

}